package org.mozhu.mboot.core.security.jasypt;

import org.apache.commons.lang3.StringUtils;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;

public class StandardConsoleInputPropertiesCollector {

    private List<StandardConsoleInputProperty> standardConsoleInputProperties = new ArrayList<>();

    public void add(StandardConsoleInputProperty standardConsoleInputProperty) {
        this.standardConsoleInputProperties.add(standardConsoleInputProperty);
    }

    public Properties collect() {
        Properties properties = new Properties();
        for (StandardConsoleInputProperty scip : standardConsoleInputProperties) {
            if (scip.getDefaultValue() != null) {
                System.out.println(MessageFormat.format("请输入{0}[{1}]，默认值为：[{2}]", scip.getTips(), scip.getKey(), scip.getDefaultValue()));
            } else {
                System.out.println(MessageFormat.format("请输入{0}[{1}]", scip.getTips(), scip.getKey()));
            }

            Scanner scan = new Scanner(System.in);
            String value = scan.nextLine();
            value = StringUtils.defaultIfEmpty(value, StringUtils.defaultIfEmpty(scip.getDefaultValue(), ""));
            scip.setValue(value);

            properties.setProperty(scip.getKey(), scip.getValue());
        }
        return properties;
    }

    public void collectIntoSystemProperties() {
        Properties properties = collect();
        for (String key : properties.stringPropertyNames()) {
            System.setProperty(key, properties.getProperty(key));
        }
    }
}
